/*
 * Copyright (C) 2010 Seapeak.Xu
 *
 * fostmq may be copied only under the terms of the GNU General
 * Public License V3, which may be found in the fostmq source kit.
 *
 * Created on: 2010-10-15
 * Author: Seapeak.Xu
 */

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>

#include "fost_thread.h"
#include "fost_logger.h"
#include "fost_notifypool.h"
#include "fost_notifythread.h"
#include "fost_notify.h"

static int _stack_size = 4;
static void *notify_listening(void *arg);
static int create_thread(notify_elt_t *notify);

static void *notify_listening(void *arg)
{
	if(NULL == arg)
	{
		log_error("File:%s,Line:%d,Function:%s.the argument is null.",
				__FILE__,__LINE__,__FUNCTION__);
		return NULL;
	}
	notify_elt_t *notify_elt = (notify_elt_t *) arg;
	if(0 != notify_event_init(notify_elt))
	{
		return NULL;
	}
	return NULL;
}

static int create_thread(notify_elt_t *notify_elt)
{
	int result = 0;
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	do
	{
		if (-1 == set_thread_stacksize(&attr, _stack_size))
		{
			log_error("File:%s,Line:%d,Function:%s.set thread stack size is error.Errno:%d,Info:%s.",
					__FILE__, __LINE__, __FUNCTION__, errno,strerror(errno));
			result = -1;
			break;
		}
	
		if (0 != pthread_create(&(notify_elt->tid), &attr, notify_listening, notify_elt))
		{
			log_error("File:%s,Line:%d,Function:%s.create thread is error.Errno:%d,Info:%s.",
					__FILE__, __LINE__, __FUNCTION__, errno,strerror(errno));
			result = -1;
			break;
		}
	}while(false);
	pthread_attr_destroy(&attr);
	return result;

}

int workthread_init(size_t size,size_t stack_size)
{

	int result = 0;
	if (0 == size || 0 == stack_size)
	{
		log_error("File:%s,Line:%d,Function:%s.the argument is error.",
				__FILE__, __LINE__, __FUNCTION__);
		return -1;
	}

	_stack_size = stack_size;
	int i;
	for( i = 0; i < size; i++)
	{
		notify_elt_t *notify_elt = g_notify_elts + i;//notifypool_pop(i);
		if(NULL == notify_elt)
		{
			result = -1;
			log_error("File:%s,Line:%d,Function:%s.get notify elt is null.index is %d.",
					__FILE__,__LINE__,__FUNCTION__,i);
			break;
		}
		if(-1 == create_thread(notify_elt))
		{
			result = -1;
			log_error("File:%s,Line:%d,Function:%s.create thread is fail.index is %d.",
					__FILE__,__LINE__,__FUNCTION__,i);
			break;
		}
	}
	return result;
}


